﻿using Kernelx.Common.Threading;
using Kernelx.Contexts.Configuration;
using System;


#if NETSTANDARD2_0
using Microsoft.Extensions.DependencyInjection;
#endif

#if NET35
using Kernelx.Common.DependencyInjection;

#endif



namespace Kernelx.Contexts
{
    /// <summary>
    /// 
    /// </summary>
    public static class WorkloadStartupContext
    {
        #region 全局操作 
        /// <summary>
        ///是否有当前上下文
        /// </summary>
        /// <returns></returns>
        public static bool HasCurrent() => _workloadStartupContext.Get() != null || _options != null;


        /// <summary>
        /// 获取当前上下文实例对象
        /// </summary>
        public static IWorkloadStartupContext Current
        {
            get
            {
                IWorkloadStartupContext obj = _workloadStartupContext.Get();
                if (obj == null && _options != null)
                    _workloadStartupContext.Set(obj = _options.Generate());
                return obj ?? throw new ApplicationException("无法获取当前上下文实例");
            }
        }

        #endregion


        #region 内置构建信息


        private static readonly ConcurrentContainer<IWorkloadStartupContext> _workloadStartupContext = new ConcurrentContainer<IWorkloadStartupContext>();

        private static WorkloadContextOptions _options;

        internal static void Configure(WorkloadContextOptions options)
        {
            if (_options != null)
                throw new ApplicationException($"不允许重复实例化{nameof(WorkloadContextOptions)}的子类类型");
            _options = options;
            _options.Services.Add(new ServiceDescriptor(typeof(WorkloadContextOptions), _options));
        }

        #endregion


    }
}
